package com.example.pixelyear.ui.frag

import android.content.Intent
import android.os.Bundle
import android.view.View
import com.example.pixelyear.R
import com.example.pixelyear.adapter.BaseAdapter
import com.example.pixelyear.adapter.YearViewAdapter
import com.example.pixelyear.bean.YearBean
import com.example.pixelyear.sql.RecordSqlUtils
import com.example.pixelyear.ui.base.BaseFragment
import com.example.pixelyear.utils.Constant
import com.example.pixelyear.utils.NumberUtils
import com.example.pixelyear.utils.Utils
import com.example.pixelyear.utils.YxsSpUtils
import com.example.pixelyear.utils.extension.gridManager
import com.socks.library.KLog
import kotlinx.android.synthetic.main.fragment_year_view.view.*

class YearViewFragment : BaseFragment() {
    private var year = 0

    private val recordSql by lazy {
        RecordSqlUtils.getInstance(mActivity)
    }

    private val mAdapter by lazy {
        YearViewAdapter(mActivity)
    }

    companion object {
        fun getInstance(year: Int): YearViewFragment {
            val frag = YearViewFragment()
            frag.arguments = Bundle().also {
                it.putInt("year", year)
            }
            return frag
        }
    }

    override fun provideContentViewId(): Int {
        return R.layout.fragment_year_view
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        rootView.YearView_Recycler.gridManager(NumberUtils.THREE)
        rootView.YearView_Recycler.adapter = mAdapter
    }

    override fun initData() {
        year = arguments?.getInt("year") ?: 0
        rootView.YearView_Year.text = "$year 年"
        val thisYear = Utils.getYear()
        if (thisYear == year)
            canLoadData()
    }

    override fun canLoadData() {
        if (mAdapter.isEmpty()) {
            for (i in 1..12) {
                mAdapter.add(
                    YearBean(
                        year, i, recordSql?.getData(year, i)
                    )
                )
            }
        }
    }

    override fun initListener() {
        mAdapter.setOnItemClickListener(object : BaseAdapter.OnItemClick<YearBean> {
            override fun click(bean: YearBean, position: Int) {
                mActivity.setResult(Constant.YEAR_VIEW_RESULT, Intent().also {
                    it.putExtra("month", bean.month)
                    it.putExtra("year", bean.year)
                })
                mActivity.finish()
            }
        })
    }

}
